package com.zgis.module.bas.util;

import java.net.InetAddress;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 * 修改记录:
 * 24-09-29     zhengchaojun             首次创建
 */

/**
 * 类描述：请求工具类
 */
public class CxRequest
{
    /**
     * 获取客户端的IP地址。
     *
     * @param req HttpServletRequest对象
     * @return 客户端的IP地址
     */
    public static String getRemoteAddr(HttpServletRequest req)
    {
        String ipAddress = req.getHeader("X-Forwarded-For");

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress))
        {
            ipAddress = req.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress))
        {
            ipAddress = req.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress))
        {
            ipAddress = req.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress))
        {
            ipAddress = req.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress))
        {
            ipAddress = req.getRemoteAddr();
        }

        // 如果获取到的IP地址是本地地址，尝试获取本地主机地址
        if ("127.0.0.1".equals(ipAddress))
        {
            try
            {
                InetAddress inet = InetAddress.getLocalHost();
                ipAddress = inet.getHostAddress();
            } catch (Exception e)
            {
                // 在这里记录日志或者进行其他异常处理
            }
        }

        // 处理可能存在的多个IP地址，取第一个
        if (ipAddress != null && ipAddress.contains(","))
        {
            ipAddress = ipAddress.split(",")[0].trim();
        }

        return ipAddress;
    }

    /**
     * 获取所有请求参数。
     *
     * @param req HttpServletRequest对象
     * @return 包含所有请求参数的Map
     */
    public static Map<String, String> getParams(HttpServletRequest req)
    {
        Map<String, String> map   = new HashMap<>();
        Enumeration<String> names = req.getParameterNames();

        while (names.hasMoreElements())
        {
            String   name   = names.nextElement();
            String[] values = req.getParameterValues(name);
            if (values != null && values.length > 0)
            {
                map.put(name, values[0]);
            }
        }

        return map;
    }
}
